package com.smzd.framework.system.business;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smzd.core.dao.IDao;
import com.smzd.framework.core.business.AbstractFGService;
import com.smzd.framework.system.dao.MeetingDao;
import com.smzd.framework.system.domain.Meeting;
import com.smzd.framework.system.domain.User;
import com.smzd.framework.utils.JsonHelper;
import com.smzd.framework.utils.db.FGRowConverter;
import com.smzd.framework.utils.db.ORPage;
import com.smzd.framework.utils.db.RPage;
import com.smzd.utils.SimpleDateTimeUtil;

@Service
public class MeetingService extends AbstractFGService<Meeting> {
	@Autowired
	private MeetingDao dao;

	@Override
	protected IDao<Meeting> getDao() {
		return dao;
	}

	@Override
	public FGRowConverter<Meeting> getConverter() {
		return MeetingService.converter;
	}

	private static FGRowConverter<Meeting> converter = new FGRowConverter<Meeting>() {
		@Override
		public Object[] convert(Meeting elem) {
			Date startTime = elem.getStartTime();
			String startTimeStr = SimpleDateTimeUtil.formatToDate(startTime);
			Date endTime = elem.getStartTime();
			String endTimeStr = SimpleDateTimeUtil.formatToDate(endTime);
			String ownerName = elem.getOwner() == null ? null : elem.getOwner().getName();
			Object[] fields = new Object[] { 
					elem.getId(), 
					elem.getName(),
					elem.getPlace(), 
					startTimeStr, 
					endTimeStr,
					elem.getDescription(), 
					ownerName,
					elem.getType()};
			return fields;
		}
	};

    @Override
    public String getListDataJson(RPage<Meeting> page) {
        @SuppressWarnings("unchecked")
        ORPage<User, Meeting> oPage = (ORPage<User, Meeting>) page;
        User user = oPage.getOwner();
        switch (user.getType()) {
        case User.USER_TYPE_MEETING_OWNER:
            return super.getListDataJson(page);
        case User.USER_TYPE_MEETING_MANAGER:
            return getAllMeetingsByPage(page);
        default:
            System.out.println("不被许可的用户类型！不返回数据！(userType=)" + user.getType());
        }

        return JsonHelper.getFailJsonString("");
    }

	private String getAllMeetingsByPage(RPage<Meeting> page) {
		dao.getAllMeetingsByPage(page);
		return page.toFlexiGridJsonString(getConverter());
	}

	public List<Meeting> getMeetingsByOwnerId(int id) {
		return dao.getMeetingsByOwnerId(id);
	}
}
